package org.jader.bolao.statistics.classificationtable;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.jader.bolao.Game;
import org.jader.bolao.Team;
import org.jader.bolao.classificationalgorithm.ClassifyByPoints;
import org.jader.bolao.statistics.ClassificationTable;

public class TeamRowByPoints extends TeamRow {

	private Map<Game,GameColumnByPoints> columnsMap;
	
	public TeamRowByPoints(ClassificationTable ct,
			Team t,
			Set<Game> games) {
		super(ct, t, games);
	}

	@Override
	protected void generateRowData(Set<Game> games) {
		columnsMap = new HashMap<Game,GameColumnByPoints>();
		ClassifyByPoints cbp = (ClassifyByPoints) classificationTable().getClassificationAlgorithm();
		Iterator<Game> it = games.iterator();
		while (it.hasNext()) {
			Game game = it.next();
			float points = cbp.getPoints(this.team(), game);
			GameColumnByPoints gc = new GameColumnByPoints(game.getTotalSum(this.team()), points);
			columnsMap.put(game, gc);
		}
	}
	
	@Override
	public GameColumnByPoints getGameColumn(Game game) {
		return columnsMap.get(game);
	}
	
	@Override
	public GameColumnByPoints getTotalColumn() {
		Iterator<GameColumnByPoints> it = columnsMap.values().iterator();
		int totalPoints = 0;
		int totalSum = 0;
		while (it.hasNext()) {
			GameColumnByPoints gc = it.next();
			totalPoints += gc.points();
			totalSum += gc.totalSum();
		}
		return new GameColumnByPoints(totalSum, totalPoints);
	}

	@Override
	public int compareTo(TeamRow arg0) {
		if (!(arg0 instanceof TeamRowByPoints)) return -1;
		TeamRowByPoints o = (TeamRowByPoints) arg0;
		float dif = o.getTotalColumn().points() - this.getTotalColumn().points();
		if (dif < 0) return -1;
		if (dif > 0) return 1;
		return this.team().getName().compareTo(o.team().getName());
	}

	public class GameColumnByPoints extends GameColumn {
		private float points = 0;
		
		public GameColumnByPoints(int sum, float points) {
			super(sum);
			this.points = points;
		}
		
		public float points() {return this.points;}
		
		@Override
		public String toString() {
			return super.toString()+" ("+Float.toString(this.points)+")";}
	}
}
